package com.itboye.zhujia.me;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.zhujia.R;
import com.itboye.zhujia.base.BaseActivity;
import com.itboye.zhujia.clipimage.ClipActivity;
import com.itboye.zhujia.constants.SPContants;
import com.itboye.zhujia.custom.RoundImageView;
import com.itboye.zhujia.util.CameraPopupWindow;
import com.itboye.zhujia.util.ImageCompress;
import com.itboye.zhujia.util.SPUtils;
import com.itboye.zhujia.util.T;
import com.itboye.zhujia.util.XImageLoader;
import com.itboye.zhujia.volley.UploadImage;
import com.itboye.zhujia.volley.UploadImage.OnUploadlistener;
import com.umeng.socialize.utils.Log;

/**
 * 个人信息
 * 
 */
public class ActivityMyData extends BaseActivity implements OnClickListener ,OnUploadlistener{
	private ImageView close_icon;// 返回图片
	private TextView add_shap_title_tv;// 标题
	private RelativeLayout user_image_layout;// 头像布局
	private RelativeLayout user_name_layout;// 昵称布局
	private RelativeLayout user_sex_layout;// 性别布局
	private RelativeLayout user_phone_layout;// 绑定手机布局
	private RelativeLayout user_move_layout;// 房源管理布局
	private RelativeLayout user_identity_layout;// 身份验证布局
	private RoundImageView usericon_im;// 头像
	private TextView usericon_nicheng;// 昵称
	private TextView usericon_sex;// 性别
	private TextView usericon_phone;// 绑定手机
	private TextView usericon_move;// 房源管理
	private TextView usericon_identity;// 身份验证

	private String phonenumber;// 保存的手机号码
	
	CameraPopupWindow mCameraPopupWindow;
	
	public static String AVARTACTION = "com.zhujia.avart";
	
	private String localSelectPath;
	
	@Override
	public int initView() {
		return 0;
	}

	@Override
	public void onMyCreate() {
		setContentView(R.layout.activity_gerendata);

		add_shap_title_tv.setText("个人信息");

		read();

	}

	/**
	 * 显示数据
	 */
	private void read() {
		//昵称
		usericon_nicheng.setText((String) SPUtils.get(ActivityMyData.this,
				null, SPContants.NICK, ""));
		//电话
		phonenumber = (String) SPUtils.get(ActivityMyData.this, null,
				SPContants.MOBILE, "");
		if (!phonenumber.equals("")){
			try {
				String hintphone = phonenumber.substring(0, 3) + "****"
						+ phonenumber.substring(7, 11);
				usericon_phone.setText(hintphone);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		initavatar();

		//性别
		String sex = (String) SPUtils.get(ActivityMyData.this, null,
				SPContants.SEX, "");
		if(!sex.equals("")){
			try {
				if(sex.equals("0")){
					usericon_sex.setText("女");
				}else if(sex.equals("1")){
					usericon_sex.setText("男");
				}else{
					usericon_sex.setText("未知");
				}
			} catch (Exception e) {
			}
		}

	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.close_icon:// 返回
			finish();
			break;
		case R.id.user_image_layout:// 头像布局
			mCameraPopupWindow=new CameraPopupWindow(ActivityMyData.this, onclicklister);
			mCameraPopupWindow.showAtLocation(
					v,
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.user_name_layout:// 昵称布局
			intent = new Intent(ActivityMyData.this, ActivityNiCheng.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.user_sex_layout:// 性别布局
			intent = new Intent(ActivityMyData.this, ActivitySex.class);
			startActivityForResult(intent, 2);
			break;
		case R.id.user_phone_layout:// 绑定手机布局

			break;
		case R.id.user_move_layout:// 房源管理布局

			break;
		case R.id.user_identity_layout:// 身份验证布局

			break;

		default:
			break;
		}

	}
	private String picture_name;

	private String fileName;
	// 使用相机拍照
		private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	public static final int IMAGE_COMPLETE = 6; // 结果
	/**
	 * 界面返回
	 *//*
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 1) {
				usericon_nicheng.setText("" + data.getStringExtra("nickname"));
			} else if(requestCode == 2){
				String sexx=data.getStringExtra("sex");
				if(sexx.equals("0")){
					usericon_sex.setText("女");
				}else if(sexx.equals("1")){
					usericon_sex.setText("男");
				}else{
					usericon_sex.setText("未知");
				}
			}else if(requestCode==6){
				UploadImage.getInstance().execute(localSelectPath,this);
				mCameraPopupWindow.dismiss();
			}else if(requestCode==CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE&&resultCode==RESULT_OK){
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile", "SD card is not avaiable/writeable right now.");
					return;
				}
				picture_name = android.text.format.DateFormat.format("yyyyMMdd_hhmmss",
						Calendar.getInstance(Locale.CHINA)) + ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
//				fileName=ImageCompress.compress(fileName);
				UploadImage.getInstance().execute(fileName,this);
				mCameraPopupWindow.dismiss();
				
			}else if (requestCode == 0) {
				*//**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 *//*
				Uri selectedImage = data.getData();
				localSelectPath = null;
//				Cursor cursor = this.getContentResolver().query(
//						data.getData(), null, null, null, null);
//				cursor.moveToFirst();
//				int columnIndex = cursor.getColumnIndex("_data");
//				localSelectPath = cursor.getString(columnIndex);
				localSelectPath=getRealPathFromURI(selectedImage);
				localSelectPath=ImageCompress.compress(localSelectPath);
				Intent intent2=new Intent(ActivityMyData.this, ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			} 
			
		}
	}*/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
//				Cursor cursor = this.getContentResolver().query(
//						data.getData(), null, null, null, null);
//				cursor.moveToFirst();
//				int columnIndex = cursor.getColumnIndex("_data");
//				localSelectPath = cursor.getString(columnIndex);
				localSelectPath=getRealPathFromURI(selectedImage);
//				localSelectPath=ImageCompress.compress(localSelectPath);
				Intent intent2=new Intent(ActivityMyData.this, ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			} 
			else if (requestCode == 3) {
				// Toast.makeText(App.ctx, "haha", 0).show();
			//	emailtext.setText("" + data.getStringExtra("email"));
			} else if (requestCode == 1) {
			//	nicktext.setText("" + data.getStringExtra("nickname"));
			}else if(requestCode==6){
				UploadImage.getInstance().execute(localSelectPath,this);
				mCameraPopupWindow.dismiss();
			}else if(requestCode==CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE&&resultCode==RESULT_OK){
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile", "SD card is not avaiable/writeable right now.");
					return;
				}
				picture_name = android.text.format.DateFormat.format("yyyyMMdd_hhmmss",
						Calendar.getInstance(Locale.CHINA)) + ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
//				fileName=ImageCompress.compress(fileName);
				UploadImage.getInstance().execute(fileName,this);
				mCameraPopupWindow.dismiss();
				
			}
		}
	}
	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					Toast.makeText(ActivityMyData.this, "请确认已经插入SD卡", 0)
							.show();
				}
				break;
			case R.id.pick_image:
				Intent intent2 = new Intent();
				intent2.setType("image/*");// 可选择图片视频
				// 修改为以下两句代码

				intent2.setAction(Intent.ACTION_PICK);
				intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
				// intent.setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				// "image/*");
				startActivityForResult(intent2, 0);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 该方法用于获取文件的真实路径从URI
	 * 从相机拍摄
	 */
	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}
	@Override
	public void OnSuccess(String resultData) {
		T.showShort(ActivityMyData.this, "上传成功");
		initavatar();
		Intent intent = new Intent(AVARTACTION);
		sendBroadcast(intent);
		
	}
	/**
	 * 头像
	 */
	private void initavatar() {
		String uri = (String) SPUtils.get(ActivityMyData.this, null,
						SPContants.AVATAR_URL, "");
		XImageLoader.load(uri, usericon_im);
		
	}

	@Override
	public void OnError(String resultData) {
		T.showShort(ActivityMyData.this, resultData);
		
	} 

}
